<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="searchForm" :inline="true" style="margin-bottom: 20px;">
      <el-row>
        <el-col>
          <el-form-item>
            <el-input
              v-model="searchForm.fileResourceName"
              placeholder="实验室原始记录单名称"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button
              type="primary"
              class="iconfont icon-fanhui"
              @click="goBack"
            >
              返回</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 表格区域 -->
    <el-table
      :data="batchData"
      stripe
      border
      style="width: 100%"
      :header-cell-style="{ background: '#ECF3FC' }"
    >
      <template slot="empty">
        <div class="table_empty">
          <div class="empty_tips">
            <span>暂无信息</span>
          </div>
        </div>
      </template>

      <el-table-column type="index" width="50" align="center" label="序号" />
      <el-table-column
        prop="projectName"
        label="项目名称"
        width="200px"
        align="center"
      />
      <el-table-column
        prop="inspectionName"
        label="受检单位"
        width="250px"
        align="center"
      />
      <el-table-column
        prop="fileResourceName"
        label="原始记录表名称"
        min-width="200"
        align="center"
      />
      <el-table-column
        prop="sampleCount"
        label="检测样品数量"
        width="120"
        align="center"
      />
      <el-table-column
        prop="sampleNos"
        label="检测样品号"
        min-width="300"
        align="center"
      />
      <el-table-column
        prop="factorCount"
        label="检测因子数量"
        width="120"
        align="center"
      />
      <el-table-column
        prop="factorNames"
        label="检测因子名称"
        min-width="300"
        align="center"
      />
      <el-table-column label="操作" fixed="right" width="250" align="center">
        <template slot-scope="{ row }">
          <div
            style="display: flex;align-items: center;justify-content: space-evenly;"
          >
            <el-button type="text" @click="handleResultEntry(row)"
              >原始记录表</el-button
            >
            <div class="erc-divider-vertical" />
            <el-button
              type="text"
              icon="el-icon-upload2"
              @click="openSpectrumUpload(row)"
              >导入谱图附件</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div style="float: right; margin-top: 20px;">
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="searchForm.pageNumber"
        :limit.sync="searchForm.pageSize"
        @pagination="handleSearch"
      />
    </div>

    <el-dialog title="选择样品号" :visible.sync="dialogVisible" width="20%">
      <el-form>
        <el-form-item label="样品号">
          <el-select
            v-model="selectedSampleNo"
            placeholder="请选择样品号"
            style="width: 100%"
          >
            <el-option
              v-for="item in sampleOptions"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSampleSelection"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 谱图附件上传弹框 -->
    <el-dialog
      title="导入谱图附件"
      :visible.sync="spectrumDialogVisible"
      width="400px"
      @close="handleSpectrumDialogClose"
    >
      <el-upload
        ref="spectrumUpload"
        class="upload-demo"
        drag
        action="/api/checkTaskGroup/pcFileUpload"
        :on-preview="handleSpectrumPreview"
        :on-remove="handleSpectrumRemove"
        :before-remove="beforeSpectrumRemove"
        :on-change="handleSpectrumChange"
        :before-upload="beforeSpectrumUpload"
        :on-success="handleSpectrumSuccess"
        name="files"
        multiple
        :file-list="spectrumFileList"
        :auto-upload="false"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>

      <div v-if="selectedSpectrumFile" style="margin-top: 10px;">
        已选择文件: {{ selectedSpectrumFile.name }}
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="spectrumDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitSpectrumFiles">
          确 定上传
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as batchesServer from "@/api/batches";
import Pagination from "@/components/Pagination";

export default {
  components: { Pagination },
  data() {
    return {
      searchForm: {
        factorName: "",
        fileResourceName: "",
        pageNumber: 1,
        pageSize: 10
      },
      batchData: [],
      total: 0,
      batchNumber: "",
      checkFactorId: "",
      checkFactorIds: "",
      checkTaskId: "",
      jobId: "",
      batchUrl: "",
      uploadedFiles: [],
      // 弹框相关数据
      dialogVisible: false,
      sampleOptions: [],
      selectedSampleNo: "",
      // 新增：谱图附件上传相关
      spectrumDialogVisible: false,
      spectrumFileList: [], // 用于回显已上传的文件
      currentUploadRow: null, // 当前上传的行数据
      uploadSuccessCount: 0,
      uploadTotalCount: 0,
      uploadFailedCount: 0
    };
  },
  created() {
    // 接收路由参数
    this.batchNumber = this.$route.params.batchNumber || "";
    this.checkFactorId = this.$route.params.checkFactorId || "";
    this.checkFactorIds = this.$route.params.checkFactorIds || "";
    this.checkTaskId = this.$route.params.checkTaskId || "";
    this.jobId = this.$route.params.jobId || "";
    this.handleSearch();
  },
  methods: {
    handleSearch() {
      if (this.batchNumber && this.batchNumber != "") {
        var params = {
          batchNumber: this.batchNumber,
          fileResourceName: this.searchForm.fileResourceName,
          pageNumber: 1,
          pageSize: 10
        };
        batchesServer.findResourceNameByCondition(params).then(res => {
          console.log("res", res);

          if (res.code === 200) {
            this.batchData = res.result.records;
            this.total = res.result.total;
          }
        });
      }
    },
    goBack() {
      this.$router.push({
        path: `/other/laboratorTask/${this.checkTaskId}`,
        query: { jobId: this.jobId }
      });
    },
    handleResultEntry(row) {
      // 跳转到表单结果录入页面
      this.$router
        .push({
          name: "ResultEntry",
          params: {
            batchNumber: row.batchNumber,
            checkFactorId: row.checkFactorId,
            checkFactorIds: row.checkFactorIds,
            checkTaskId: this.checkTaskId,
            jobId: this.jobId,
            batcData: row
          }
        })
        .catch(err => {
          console.error("路由跳转失败:", err);
          this.$message.error("页面跳转失败");
        });
    },

    // 打开谱图附件上传弹框
    openSpectrumUpload(row) {
      this.currentUploadRow = row;
      this.spectrumDialogVisible = true;
      this.spectrumFileList = [];

      // 如果已有上传的文件，进行回显
      this.fetchExistingSpectrumFiles(row);
    },

    // 获取已存在的谱图文件进行回显
    fetchExistingSpectrumFiles(row) {
      // 检查行数据中是否有 batchUrl 字段
      if (row.batchUrl) {
        // 解析 batchUrl 字段，通常是逗号分隔的文件URL列表
        const urls = row.batchUrl.split(",").filter(url => url.trim() !== "");

        // 构造文件列表用于回显
        this.spectrumFileList = urls.map((url, index) => {
          // 从URL中提取文件名，如果没有则使用默认名称
          const fileName =
            this.extractFileNameFromUrl(url) || `附件${index + 1}`;

          return {
            name: fileName,
            url: url.trim(),
            status: "success" // 标记为已上传成功状态
          };
        });
      }
    },
    extractFileNameFromUrl(url) {
      if (!url) return "";

      // 尝试从URL中提取文件名
      const urlParts = url.split("/");
      const fileName = urlParts[urlParts.length - 1];

      // 如果文件名存在且不为空
      if (fileName && fileName !== "") {
        return decodeURIComponent(fileName);
      }

      return "";
    },

    // 处理谱图文件预览
    handleSpectrumPreview(file) {
      window.open(file.url);
    },

    // 处理谱图文件移除
    handleSpectrumRemove(file, fileList) {
      this.spectrumFileList = fileList;
    },

    // 移除文件前确认
    beforeSpectrumRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },

    // 处理谱图文件变化
    handleSpectrumChange(file, fileList) {
      this.spectrumFileList = fileList;
    },

    // 添加文件上传成功的处理方法
    handleSpectrumSuccess(response, file, fileList) {
      if (response && response.code === 200) {
        // 为上传成功的文件添加URL
        file.url = response.result[0];
        this.$message.success(`文件 ${file.name} 上传成功`);

        // 增加成功计数
        this.uploadSuccessCount++;
      } else {
        this.$message.error(response.message || `文件 ${file.name} 上传失败`);
        this.uploadFailedCount++;
      }

      // 检查是否所有文件都已处理完成
      if (
        this.uploadSuccessCount + this.uploadFailedCount ===
        this.uploadTotalCount
      ) {
        // 所有文件处理完成
        if (this.uploadFailedCount === 0) {
          // 全部成功，调用 checkFactor
          this.checkFactor();
        } else {
          // 全部失败
          this.$message.error("所有文件上传失败，无法提交");
        }
      }
    },
    // 谱图文件上传前检查
    beforeSpectrumUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.error("文件大小不能超过 10MB!");
        return false;
      }
      return true;
    },

    // 提交谱图文件
    submitSpectrumFiles() {
      // 获取所有需要上传的文件（排除已经成功的文件）
      const filesToUpload = this.spectrumFileList.filter(file => !file.url);

      // // 即使没有新文件也要允许提交，但需要有文件存在
      // if (this.spectrumFileList.length === 0) {
      //   this.$message.warning("请至少选择一个文件");
      //   return;
      // }

      // 如果有新文件需要上传，则初始化上传计数器并触发上传
      if (filesToUpload.length > 0) {
        this.uploadSuccessCount = 0;
        this.uploadTotalCount = filesToUpload.length;
        this.uploadFailedCount = 0;

        // 触发上传
        this.$refs.spectrumUpload.submit();
      } else {
        // 没有新文件需要上传，直接调用checkFactor提交现有文件
        this.checkFactor();
      }
    },

    checkFactor() {
      // 收集所有文件的URL（包括已存在的和新上传的）
      const uploadedUrls = this.spectrumFileList
        .filter(file => file.url) // 只选择有URL的文件
        .map(file => file.url);

      // if (uploadedUrls.length === 0) {
      //   this.$message.warning("没有可提交的文件");
      //   return;
      // }

      batchesServer
        .checkFactorFileBatch({
          batchNumber: this.batchNumber,
          checkFactorIds: this.currentUploadRow.checkFactorIds,
          batchUrl: uploadedUrls.join(",")
        })
        .then(res => {
          console.log(res);
          if (res.code === 200) {
            this.$message({
              type: "success",
              message: "上传成功!"
            });
            this.handleSearch();
            // 关闭弹框
            this.spectrumDialogVisible = false;
          } else {
            this.$message.error("上传失败!");
          }
        })
        .catch(err => {
          console.error(err);
          this.$message.error("上传失败!");
        });
    },

    // 关闭弹框时的处理
    handleSpectrumDialogClose() {
      this.spectrumFileList = [];
      this.currentUploadRow = null;
      if (this.$refs.spectrumUpload) {
        this.$refs.spectrumUpload.clearFiles();
      }
    }
  }
};
</script>

<style scoped lang="scss">
.el-form-item {
  margin-bottom: 0;
}

.el-form-item__label {
  font-weight: normal;
}

.el-table {
  margin-bottom: 20px;
}

.table_empty {
  text-align: center;
  padding: 40px 0;
}

.empty_tips {
  color: #999;
  font-size: 14px;
}

.erc-divider-vertical {
  display: inline-block;
  width: 1px;
  height: 14px;
  background-color: #ebeef5;
  vertical-align: middle;
  margin: 0 10px;
}

::v-deep .el-table th {
  background-color: #ecf3fc !important;
  color: #333;
  font-weight: bold;
}

::v-deep .el-table td {
  padding: 12px 0;
}

::v-deep .el-table .cell {
  white-space: pre-line;
  word-break: break-all;
}

.inline-upload {
  display: inline-block;
  vertical-align: middle;
}

.inline-upload ::v-deep .el-upload {
  display: inline-block;
}
</style>
